import query from './atom/db/query';
import count from './atom/db/count';

declare const action_id: string;
declare const session_id: string;
declare const spaceid: string;

interface Message {
	flag: number,//0|1
	class_id: string,
	page_size: number,
	page_no: number,
	//0
	exam_subjects_id?: string,
	//1
	student_name?: string,
	student_ids?: string[]
}

async function atom(msg: Message) {
	const systemid = '5981';
	console.log(msg);
	if (msg.flag == 0) {
		const q1 = query(action_id, session_id, spaceid, systemid);
		//依据“考试科目编号”查<考场编排>得到“编排编号”（值多个)
		q1.prepare('arrange_exam_room', ['layout_no'], { exam_subjects_id: msg.exam_subjects_id }, 0, 1);
		const [arrange_exam_rooms] = await q1.exec();
		const layout_nos = arrange_exam_rooms.map((d: any) => {
			return d.layout_no;
		});
		console.log(layout_nos, '--<1>--');

		//依据“编排编号”（值多个）查<学生编排>得到“学号”（值多个）
		const q2 = query(action_id, session_id, spaceid, systemid);
		q2.prepare('arrange_exam_student', ['student_id'], { layout_no: { $in: layout_nos } }, 0, 1);
		const [arrange_exam_student] = await q2.exec();
		const student_ids = arrange_exam_student.map((d: any) => {
			return d.student_id;
		});
		console.log(student_ids, '--<2>--', JSON.stringify({ class_id: msg.class_id, student_id: { $in: student_ids } }));

		//依据“教学班编号”、“学号”过滤<教学班学生>，得到学生数据
		const q3 = query(action_id, session_id, spaceid, '5991');
		q3.prepare('teachingclass_student', ['student_id', 'student_name', 'student_type', 'class_name', 'sex', 'student_no'], { class_id: msg.class_id, student_id: { $nin: student_ids } }, msg.page_size, msg.page_no);
		const [teachingclass_students] = await q3.exec();
		console.log(teachingclass_students, '--<3>--');

		const c = count(action_id, session_id, spaceid, '5991');
		c.prepare('teachingclass_student', { class_id: msg.class_id, student_id: { $nin: student_ids } });
		const tc = await c.exec();
		return { t: teachingclass_students, c: tc[0], student_ids: student_ids };
	} else if (msg.flag == 1) {
		//依据“教学班编号”、“学号”过滤、学生姓名查询<教学班学生>，得到学生数据
		const q3 = query(action_id, session_id, spaceid, '5991');
		console.log(JSON.stringify({ student_name: { $regex: '.*' + msg.student_name + '.*', $options: "i" }, class_id: msg.class_id, student_id: { $nin: msg.student_ids } }));
		q3.prepare('teachingclass_student', ['student_id', 'student_name', 'student_type', 'class_name', 'sex', 'student_no'], { student_name: { $regex: '.*' + msg.student_name + '.*', $options: "i" }, class_id: msg.class_id, student_id: { $nin: msg.student_ids } }, msg.page_size, msg.page_no);
		const [teachingclass_students] = await q3.exec();
		console.log(teachingclass_students, '--<3>--');

		const c = count(action_id, session_id, spaceid, '5991');
		c.prepare('teachingclass_student', { student_name: { $regex: '.*' + msg.student_name + '.*', $options: "i" }, class_id: msg.class_id, student_id: { $nin: msg.student_ids } });
		const tc = await c.exec();
		return { t: teachingclass_students, c: tc[0] };
	}
}
